package com.chen.dao;
/*
 *@description:描述
 *@author:陈琰
 *@time：2021/8/24  16:34
 */

import com.chen.domain.LoginUser;
import com.chen.domain.RegeditUser;
import com.chen.domain.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDao {
    //登录时查找数据库有无对应的账号密码
    public User findUser(LoginUser loginUser){
        try {
            QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
            User user = queryRunner.query("select * from user where username = ? and password = ?",
                    new BeanHandler<User>(User.class), loginUser.getUsername(), loginUser.getPassword());
            return user;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    //注册时查找数据库有无对应的账号
    public User findUserName(RegeditUser regeditUser) {
        try {
            QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
            User user = queryRunner.query("select * from user where username = ?",
                    new BeanHandler<User>(User.class), regeditUser.getUsername());
            return user;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    //注册用户进数据库
    public User showAdd(RegeditUser regeditUser) {
        try {
            String username = regeditUser.getUsername();
            String password = regeditUser.getPassword();
            String role = regeditUser.getRole();
            String sql = "INSERT INTO user (username,password,role)VALUES(?,?,?)";
            Object[] params = {username, password ,role};
            QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
            int row = queryRunner.update(sql, params);

            String sql2 = "select * from user where username =? and password = ?";
            Object[] params2 = {username, password};
            User user = queryRunner.query(sql2,new BeanHandler<User>(User.class),params2);
            System.out.println(user.toString());
            return user;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }
}
